package org.fight.net.session;

import java.net.SocketAddress;

import org.apache.commons.lang3.ArrayUtils;
import org.fight.actor.ActorMsg;
import org.fight.actor.ActorMsgTypeEnum;
import org.fight.cache.SessionCache;
import org.fight.net.EncryptionAndDecryptionUtil;
import org.fight.net.KcpCodec;
import org.fight.net.KcpConstant;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.third.kcp.KCP;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

import akka.actor.ActorRef;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

public class KcpSession extends ISession {

	static Log log = LogFactory.get(KcpSession.class);

	protected Channel channel;

	public KcpSession(Channel channel) {
		super();
		this.channel = channel;
	}

	// ----------------------------------------
	@Override
	public String getId() {
		return channel.id().asShortText();
	}

	@Override
	public SocketAddress localAddress() {
		return channel.localAddress();
	}

	@Override
	public SocketAddress remoteAddress() {
		return channel.remoteAddress();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Channel getChannel() {
		// TODO Auto-generated method stub
		return channel;
	}

	@Override
	public void setChannel(Object channel) {
		this.channel = (Channel) channel;
	}

	@Override
	public void close() {
		ActorRef actor = getAttr(KcpConstant.ACTOR);
		// 关闭一个Actor
		actor.tell(akka.actor.PoisonPill.getInstance(), ActorRef.noSender());
		// 清除缓存
		SessionCache.me().remove(getAttr(KcpConstant.CONV));
		// 清除属性
		clearAttr();
	}

	@Override
	public boolean isWritable() {
		return channel.isWritable();
	}

	@Override
	public boolean isOpen() {
		return channel.isOpen();
	}

	@Override
	public boolean isActive() {
		return channel.isActive();
	}

	@Override
	protected void writeAndFlush(IMessage msg) {
		ActorRef actor = getAttr(KcpConstant.ACTOR);
		actor.tell(new ActorMsg(ActorMsgTypeEnum.KCP_SEND, msg), ActorRef.noSender());
	}

}
